//
//  LoginView.swift
//  SwiftUI+MVVM+Repository
//
//  Created by 高强 on 2024/9/10.
//

import SwiftUI

struct LoginView: View {
    @ObservedObject var viewModel: LoginViewModel
    
    var body: some View {
        NavigationView {  // 添加 NavigationView
            
            VStack(spacing: 15) {
                HStack {
                    Text("昵称：")
                        .foregroundColor(.secondary)
                    
                    TextField("请输入昵称", text: $viewModel.name)
                        .padding(10)
                        .frame(height: 50)
                        .textFieldStyle(RoundedBorderTextFieldStyle())
                        .autocapitalization(.none)  // 禁用自动大写
                }
                .padding(.horizontal, 20)
                //.padding(EdgeInsets(top: 0, leading: 20, bottom: 0, trailing: 20))
                
                HStack {
                    Text("密码：").foregroundColor(.secondary)
                    SecureField("请输入密码", text: $viewModel.password)
                        .padding(10)
                        .frame(height: 50)
                        .textFieldStyle(RoundedBorderTextFieldStyle())
                }
                .padding(.horizontal, 20)
                //.padding(EdgeInsets(top: 0, leading: 20, bottom: 0, trailing: 20))
                
                Button(action: {
                    // 执行登录逻辑
                    viewModel.login()
                }) {
                    Text("登录").bold()
                        .font(.system(size: 40, design: .rounded))
                        .shadow(radius: 1)
                }
                .alert(isPresented: $viewModel.showError) {
                    Alert(title: Text("错误"), message: Text(viewModel.errorMessage), dismissButton: .default(Text("确定")))
                }
                
                // 跳转到 HomeView
                NavigationLink(destination: AppRouter.shared.jump(to: .home)
                               //HomeView()
                               //.navigationBarBackButtonHidden(true) // 隐藏返回按钮
                               //.navigationBarHidden(true) // 隐藏导航栏
                               , isActive: $viewModel.isLoginSuccessful) {
                    Text("")  // 空的内容避免 UI 错误
                }
            }
            .offset(y: -150)
            .navigationBarTitle(Text("TextField"))
        }
    }
}
